package com.sz.virtualbank.web.controller.loan;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.sz.virtualbank.common.annotation.LoginRequired;
import com.sz.virtualbank.common.result.CommonResponse;
import com.sz.virtualbank.dao.entity.LoanRecord;
import com.sz.virtualbank.dao.entity.LoanRepaymentPlan;
import com.sz.virtualbank.dao.entity.User;
import com.sz.virtualbank.service.loan.LoanService;
import com.sz.virtualbank.service.user.UserService;
import com.sz.virtualbank.web.vo.loan.EarlyRepaymentReqVO;
import com.sz.virtualbank.web.vo.loan.LoanApplyReqVO;
import com.sz.virtualbank.web.vo.loan.LoanRepayReqVO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;

/**
 * 贷款相关接口
 *
 * @author Claude
 */
@RestController
@RequestMapping("/api/loan")
@Slf4j
@Api(tags = "贷款接口")
public class LoanController {

    @Autowired
    private LoanService loanService;

    @Autowired
    private UserService userService;

    /**
     * 贷款申请
     */
    @PostMapping("/apply")
    @ApiOperation("贷款申请")
    @LoginRequired
    public CommonResponse<LoanRecord> applyLoan(@RequestBody @Valid LoanApplyReqVO reqVO,
                                                HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        LoanRecord loanRecord = loanService.applyLoan(user.getId(), reqVO.getAmount(),
                reqVO.getLoanTerm(), reqVO.getPurpose(), reqVO.getRepaymentMethod());

        return CommonResponse.success(loanRecord);
    }

    /**
     * 查询贷款列表
     */
    @GetMapping("/list")
    @ApiOperation("查询贷款列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "status", value = "贷款状态", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "size", value = "每页条数", dataType = "Integer", paramType = "query", required = true)
    })
    @LoginRequired
    public CommonResponse<Map<String, Object>> getLoanList(@RequestParam(required = false) Integer status,
                                                           @RequestParam Integer page,
                                                           @RequestParam Integer size,
                                                           HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, Object> result = loanService.getLoanList(user.getId(), status, page, size);
        return CommonResponse.success(result);
    }

    /**
     * 查询贷款详情
     */
    @GetMapping("/{id}")
    @ApiOperation("查询贷款详情")
    @LoginRequired
    public CommonResponse<Map<String, Object>> getLoanDetail(@PathVariable Long id,
                                                             HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, Object> result = loanService.getLoanDetail(id, user.getId());
        return CommonResponse.success(result);
    }

    /**
     * 查询贷款还款计划
     */
    @GetMapping("/repayment-plan/{loanId}")
    @ApiOperation("查询贷款还款计划")
    @LoginRequired
    public CommonResponse<List<LoanRepaymentPlan>> getRepaymentPlan(@PathVariable Long loanId,
                                                                    HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        List<LoanRepaymentPlan> plans = loanService.getRepaymentPlan(loanId, user.getId());
        return CommonResponse.success(plans);
    }

    /**
     * 贷款还款
     */
    @PostMapping("/repay")
    @ApiOperation("贷款还款")
    @LoginRequired
    public CommonResponse<String> repayLoan(@RequestBody @Valid LoanRepayReqVO reqVO,
                                            HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        String tradeNo = loanService.repayLoan(user.getId(), reqVO.getLoanId(),
                reqVO.getRepaymentPlanId(), reqVO.getAmount(), reqVO.getPaymentPassword());

        return CommonResponse.success(tradeNo);
    }

    /**
     * 提前还款试算
     */
    @GetMapping("/early-repayment/calculate")
    @ApiOperation("提前还款试算")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loanId", value = "贷款ID", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "repayDate", value = "还款日期", dataType = "String", paramType = "query", required = true)
    })
    @LoginRequired
    public CommonResponse<Map<String, Object>> calculateEarlyRepayment(@RequestParam Long loanId,
                                                                       @RequestParam String repayDate,
                                                                       HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        Map<String, Object> result = loanService.calculateEarlyRepayment(loanId, user.getId(), repayDate);
        return CommonResponse.success(result);
    }

    /**
     * 提前还款
     */
    @PostMapping("/early-repayment")
    @ApiOperation("提前还款")
    @LoginRequired
    public CommonResponse<String> earlyRepayment(@RequestBody @Valid EarlyRepaymentReqVO reqVO,
                                                 HttpServletRequest request) {
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        User user = userService.getCurrentUser(token);

        String tradeNo = loanService.earlyRepayment(user.getId(), reqVO.getLoanId(),
                reqVO.getAmount(), reqVO.getPaymentPassword());

        return CommonResponse.success(tradeNo);
    }

    /**
     * 贷款审批 (管理员接口)
     */
    @PostMapping("/approve/{loanId}")
    @ApiOperation("贷款审批")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "loanId", value = "贷款ID", dataType = "Long", paramType = "path", required = true),
            @ApiImplicitParam(name = "approved", value = "是否批准", dataType = "Boolean", paramType = "query", required = true),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", paramType = "query")
    })
    @LoginRequired
    public CommonResponse<Boolean> approveLoan(@PathVariable Long loanId,
                                               @RequestParam Boolean approved,
                                               @RequestParam(required = false) String remark) {
        // TODO: 实际应用中需要进行管理员权限校验

        boolean result = loanService.approveLoan(loanId, approved, remark);
        return CommonResponse.success(result);
    }
}
